package com.hengxinguotong.zhihuichengjian.ui.tower.data;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.LiveDataAlarmAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.LiveDataAlarm;
import com.hengxinguotong.zhihuichengjian.bean.TowerLive;
import com.hengxinguotong.zhihuichengjian.bean.TowerLiveRes;
import com.hengxinguotong.zhihuichengjian.ui.tower.OnFragmentInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.TopScrollView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link TowerDataLiveFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 * 实时数据
 */
public class TowerDataLiveFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String PARAM = "equipmentId";

    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.mTopScrollView)
    TopScrollView mTopScrollView;
    @BindView(R.id.alarm_rv)
    RecyclerView alarmRv;
    @BindView(R.id.monitor_time_tv)
    HXTextView monitorTimeTv;
    @BindView(R.id.height_tv)
    HXTextView heightTv;
    @BindView(R.id.extent_tv)
    HXTextView extentTv;
    @BindView(R.id.angle_tv)
    HXTextView angleTv;
    @BindView(R.id.weight_tv)
    HXTextView weightTv;
    @BindView(R.id.weight_percent_tv)
    HXTextView weightPercentTv;
    @BindView(R.id.wind_speed_tv)
    HXTextView windSpeedTv;
    @BindView(R.id.tilt_tv)
    HXTextView tiltTv;

    // TODO: Rename and change types of parameters
    private String equipmentId;

    private OnFragmentInteractionListener mListener;

    private List<LiveDataAlarm> liveDataAlarmList;
    private LiveDataAlarmAdapter liveDataAlarmAdapter;

    public TowerDataLiveFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param Parameter .
     * @return A new instance of fragment TowerDataLiveFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TowerDataLiveFragment newInstance(String param) {
        TowerDataLiveFragment fragment = new TowerDataLiveFragment();
        Bundle args = new Bundle();
        args.putString(PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    TowerLive towerLive = (TowerLive) msg.obj;
                    mListener.onUpdateTower(towerLive.getHeight(), towerLive.getExtent());
                    bindData(towerLive);
                    break;
            }
        }
    };

    private void bindData(TowerLive datas) {
        if(datas.getAlarmArray() == null || datas.getAlarmArray().size() <= 0){
            liveDataAlarmList.add(getDefaultAlarm());
        }else {
            liveDataAlarmList = datas.getAlarmArray();
        }
        liveDataAlarmAdapter.setDataList(liveDataAlarmList);
        monitorTimeTv.setText(datas.getTime());
        heightTv.setText(datas.getHeight() + "米");
        extentTv.setText(datas.getExtent() + "米");
        angleTv.setText(datas.getAngle() + "度");
        weightTv.setText(datas.getWeight() + "千克");
        weightPercentTv.setText(datas.getPercent() + "%");
        windSpeedTv.setText(datas.getWindSpeed() + "米/秒");
        tiltTv.setText(datas.getObliquity() + "度");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            equipmentId = getArguments().getString(PARAM);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tower_data_live, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);

        liveDataAlarmList = new ArrayList<>();
        liveDataAlarmAdapter = new LiveDataAlarmAdapter(getActivity(), liveDataAlarmList);
        alarmRv.setAdapter(liveDataAlarmAdapter);
        alarmRv.setItemAnimator(new DefaultItemAnimator());
        alarmRv.setLayoutManager(getLayoutManager());
    }

    private LinearLayoutManager getLayoutManager(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return  layoutManager;
    }

    private LiveDataAlarm getDefaultAlarm(){
        LiveDataAlarm liveDataAlarm = new LiveDataAlarm();
        liveDataAlarm.setType(1);
        List<String> data = new ArrayList<>();
        data.add("全部正常");
        liveDataAlarm.setData(data);
        return liveDataAlarm;
    }

    /**
     * 主页面下拉刷新操作监听
     */
    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {

        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getTowerRealTime("搜索中…");
            }
        }, 500);
    }

    public void getTowerRealTime(String alert) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("equipmentId", equipmentId);
        Utils.requestData(alert, getActivity(), "/towercrane/getTowerRealTime/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TowerLiveRes res = gson.fromJson(json, TowerLiveRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

}
